﻿/*
 *author:keily ,department 2,wuda geo
 *date:2013-1-24
 *description:文件操作类
 */

using System;
using System.IO;
using System.Text;

namespace GeoWeb.Common
{
    /// <summary>
    /// geo 文件、目录操作类
    /// </summary>
    public class IOHelper
    {
        #region 目录操作
        /// <summary>
        /// 获取指定目录的子目录名称
        /// </summary>
        /// <param name="directoryPath">目录路径</param>
        /// <returns>返回子目录名称数组</returns>
        public static string[] GetDirs(string directoryPath)
        {
            return Directory.GetDirectories(directoryPath);
        }
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="destDirectory">目录路径</param>
        /// <returns>是否成功</returns>
        public static bool CreateDir(string destDirectory)
        {
            if (!string.IsNullOrEmpty(destDirectory) && !Directory.Exists(destDirectory))
            {
                Directory.CreateDirectory(destDirectory);
                return true;
            }
            return false;
        }
        /// <summary>
        /// 拷贝目录
        /// </summary>
        /// <param name="strFromDirectory">源目录路径</param>
        /// <param name="strToDirectory">目标目录路径</param>
        /// <returns>是否成功</returns>
        public static bool CopyDir(string strFromDirectory, string strToDirectory)
        {
            Directory.CreateDirectory(strToDirectory);
            if (!Directory.Exists(strFromDirectory))
            {
                return false;
            }
            string[] directories = Directory.GetDirectories(strFromDirectory);
            if (directories.Length > 0)
            {
                string[] array = directories;
                for (int i = 0; i < array.Length; i++)
                {
                    string text = array[i];
                    CopyDir(text, strToDirectory + text.Substring(text.LastIndexOf("\\")));
                }
            }
            string[] files = Directory.GetFiles(strFromDirectory);
            if (files.Length > 0)
            {
                string[] array2 = files;
                for (int j = 0; j < array2.Length; j++)
                {
                    string text2 = array2[j];
                    File.Copy(text2, strToDirectory + text2.Substring(text2.LastIndexOf("\\")));
                }
            }
            return true;
        }
        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="dirFullPath">目录路径</param>
        /// <returns>是否成功</returns>
        public static bool DeleteDir(string dirFullPath)
        {
            if (Directory.Exists(dirFullPath))
            {
                Directory.Delete(dirFullPath, true);
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取指定目录下一级子目录的文件
        /// </summary>
        /// <param name="dirFullPath">目录路径</param>
        /// <returns>下级目录文件</returns>
        public static string[] GetDirFiles(string dirFullPath)
        {
            if (Directory.Exists(dirFullPath))
            {
                return Directory.GetFiles(dirFullPath);
            }
            return null;
        }
        /// <summary>
        /// 获取指定目录下的文件，搜索模式
        /// </summary>
        /// <param name="dirFullPath">文件路径</param>
        /// <param name="so">搜索模式</param>
        /// <returns>文件</returns>
        public static string[] GetDirFiles(string dirFullPath, SearchOption so)
        {
            if (Directory.Exists(dirFullPath))
            {
                return Directory.GetFiles(dirFullPath, "*.*", so);
            }
            return null;
        }
        /// <summary>
        /// 获取指定目录下的文件，搜索匹配表达式
        /// </summary>
        /// <param name="dirFullPath">文件路径</param>
        /// <param name="searchPattern">搜索匹配表达式</param>
        /// <returns>文件</returns>
        public static string[] GetDirFiles(string dirFullPath, string searchPattern)
        {
            if (Directory.Exists(dirFullPath))
            {
                return Directory.GetFiles(dirFullPath, searchPattern);
            }
            return null;
        }
        /// <summary>
        /// 获取指定目录下的文件
        /// </summary>
        /// <param name="dirFullPath">文件路径</param>
        /// <param name="searchPattern">搜索匹配表达式</param>
        /// <param name="isSearchChild">是否搜索子目录</param>
        /// <returns></returns>
        public static string[] GetDirFiles(string dirFullPath, string searchPattern, bool isSearchChild)
        {
            if (Directory.Exists(dirFullPath))
            {
                return Directory.GetFiles(dirFullPath, searchPattern,
                    isSearchChild ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
            }
            return null;
        }
        /// <summary>
        /// 是否存在目录
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <returns></returns>
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }
        /// <summary>
        /// 目录是否为空
        /// </summary>
        /// <param name="directoryPath">目录路径</param>
        /// <returns>是否为空</returns>
        public static bool IsEmptyDirectory(string directoryPath)
        {
            string[] fileNames = GetDirFiles(directoryPath);
            if (fileNames.Length > 0)
            {
                return false;
            }
            string[] dirs = GetDirs(directoryPath);
            return dirs.Length <= 0;
        }
        /// <summary>
        /// 检查是否包含文件
        /// </summary>
        /// <param name="directoryPath">目录路径</param>
        /// <param name="searchPattern">匹配模式</param>
        /// <returns>是否包含</returns>
        public static bool ContainFile(string directoryPath, string searchPattern)
        {
            string[] fileNames = GetDirFiles(directoryPath, searchPattern, true);
            return fileNames.Length != 0;
        }
        /// <summary>
        /// 检查是否包含文件
        /// </summary>
        /// <param name="directoryPath">目录路径</param>
        /// <param name="searchPattern">匹配模式</param>
        /// <param name="isSearchChild">是否搜索子目录</param>
        /// <returns></returns>
        public static bool ContainFile(string directoryPath, string searchPattern, bool isSearchChild)
        {
            string[] fileNames = GetDirFiles(directoryPath, searchPattern, isSearchChild);
            return fileNames.Length != 0;
        }
        /// <summary>
        /// 获取当前目录
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentDirectory()
        {
            return Directory.GetCurrentDirectory();
        }
        /// <summary>
        /// 设置当前目录
        /// </summary>
        /// <param name="path">需要设置的目录路径</param>
        public static void SetCurrentDirectory(string path)
        {
            Directory.SetCurrentDirectory(path);
        }
        /// <summary>
        /// 获取包含在路径中不允许字符数组
        /// </summary>
        /// <returns></returns>
        public static char[] GetInvalidPathChars()
        {
            return Path.GetInvalidPathChars();
        }
        /// <summary>
        /// 获取当前驱动器列表
        /// </summary>
        /// <returns></returns>
        public static DriveInfo[] GetAllDrives()
        {
            return DriveInfo.GetDrives();
        }

        #endregion

        #region 文件操作

        /// <summary>
        /// 删除指定文件
        /// </summary>
        /// <param name="fileFullPath">文件完整路径</param>
        /// <returns>删除是否成功</returns>
        public static bool DeleteFile(string fileFullPath)
        {
            if (File.Exists(fileFullPath))
            {
                if (File.GetAttributes(fileFullPath) == FileAttributes.Normal)
                {
                    File.Delete(fileFullPath);
                }
                else
                {
                    File.SetAttributes(fileFullPath, FileAttributes.Normal);
                    File.Delete(fileFullPath);
                }
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取指定完整路径下的文件名
        /// </summary>
        /// <param name="fileFullPath">文件的完整路径</param>
        /// <returns>文件名</returns>
        public static string GetFileName(string fileFullPath)
        {
            if (File.Exists(fileFullPath))
            {
                FileInfo fileInfo = new FileInfo(fileFullPath);
                return fileInfo.Name;
            }
            return null;
        }
        /// <summary>
        /// 获取指定完整路径下的文件名
        /// </summary>
        /// <param name="fileFullPath">文件的完整路径</param>
        /// <param name="includeExtension">是获取获取扩展名(后缀)</param>
        /// <returns>文件名</returns>
        public static string GetFileName(string fileFullPath, bool includeExtension)
        {
            if (!File.Exists(fileFullPath))
            {
                return null;
            }
            FileInfo fileInfo = new FileInfo(fileFullPath);
            if (includeExtension)
            {
                return fileInfo.Name;
            }
            return fileInfo.Name.Replace(fileInfo.Extension, "");
        }
        /// <summary>
        /// 获取指定文件的新名称，命名规则后面加数字
        /// 如 file.xml 新名称为 file1.xml 如果存在file1.xml，则命名为file2.xml
        /// </summary>
        /// <param name="fileFullPath">文件路径</param>
        /// <returns>文件路径</returns>
        public static string GetNewFileFullName(string fileFullPath)
        {
            if (File.Exists(fileFullPath))
            {
                FileInfo fileInfo = new FileInfo(fileFullPath);
                string str = fileFullPath.Replace(fileInfo.Extension, "");
                for (int i = 0; i < 1000; i++)
                {
                    fileFullPath = str + i.ToString() + fileInfo.Extension;
                    if (!File.Exists(fileFullPath))
                    {
                        break;
                    }
                }
            }
            return fileFullPath;
        }
        /// <summary>
        /// 获取文件的后缀 如 d:\svn\file.xml ,得到 .xml
        /// </summary>
        /// <param name="fileFullPath">文件完全路径</param>
        /// <returns>后缀</returns>
        public static string GetFileExtension(string fileFullPath)
        {
            if (File.Exists(fileFullPath))
            {
                FileInfo fileInfo = new FileInfo(fileFullPath);
                return fileInfo.Extension;
            }
            return null;
        }
        /// <summary>
        /// 利用系统默认程序打开文件，如 txt就用notepad，html有用默认浏览器
        /// </summary>
        /// <param name="fileFullPath">文件路径</param>
        /// <returns>是否成功</returns>
        public static bool OpenFile(string fileFullPath)
        {
            if (File.Exists(fileFullPath))
            {
                System.Diagnostics.Process.Start(fileFullPath);
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取文件的大小
        /// </summary>
        /// <param name="fileFullPath">文件路径</param>
        /// <returns>文件大小</returns>
        public static string GetFileSize(string fileFullPath)
        {
            if (!File.Exists(fileFullPath))
            {
                return null;
            }
            FileInfo fileInfo = new FileInfo(fileFullPath);
            long length = fileInfo.Length;
            if (length > 1073741824L)
            {
                return Convert.ToString(Math.Round(((double)length + 0.0) / 1073741824.0, 2)) + " GB";
            }
            if (length > 1048576L)
            {
                return Convert.ToString(Math.Round(((double)length + 0.0) / 1048576.0, 2)) + " MB";
            }
            return Convert.ToString(Math.Round(((double)length + 0.0) / 1024.0, 2)) + " KB";
        }
        /// <summary>
        /// 以文件流的方式打开文件，并返回为数组
        /// </summary>
        /// <param name="fileFullPath">文件路径</param>
        /// <returns>二进制数组</returns>
        public static byte[] FileToStreamByte(string fileFullPath)
        {
            byte[] array = null;
            if (File.Exists(fileFullPath))
            {
                FileStream fileStream = new FileStream(fileFullPath, FileMode.Open);
                array = new byte[fileStream.Length];
                fileStream.Read(array, 0, array.Length);
                fileStream.Close();
            }
            return array;
        }
        /// <summary>
        /// 将二进制数组写入到文件
        /// </summary>
        /// <param name="createFileFullPath">需要写入文件的路径，包括文件名</param>
        /// <param name="streamByte">文件流字节数组</param>
        /// <returns>是否成功</returns>
        public static bool ByteStreamToFile(string createFileFullPath, byte[] streamByte)
        {
            if (!File.Exists(createFileFullPath))
            {
                FileStream fileStream = File.Create(createFileFullPath);
                fileStream.Write(streamByte, 0, streamByte.Length);
                fileStream.Close();
                return true;
            }
            return false;
        }
        /// <summary>
        /// 将二进制数组写入到文件
        /// </summary>
        /// <param name="createFileFullPath">需要写入文件的路径，包括文件名</param>
        /// <param name="streamByte">文件流字节数组</param>
        /// <param name="fileExistsDelete">是否文件存在就删除重写</param>
        /// <returns>是否成功</returns>
        public static bool ByteStreamToFile(string createFileFullPath, byte[] streamByte, bool fileExistsDelete)
        {
            if (File.Exists(createFileFullPath) && fileExistsDelete && !DeleteFile(createFileFullPath))
            {
                return false;
            }
            FileStream fileStream = File.Create(createFileFullPath);
            fileStream.Write(streamByte, 0, streamByte.Length);
            fileStream.Close();
            return true;
        }
        /// <summary>
        /// 读取并写入文件
        /// </summary>
        /// <param name="pathRead">源文件路径</param>
        /// <param name="pathWrite">目标文件路径</param>
        /// <param name="replaceStrings">需要替代的字符</param>
        public static void ReadAndWriteFile(string pathRead, string pathWrite, System.Collections.Generic.Dictionary<string, string> replaceStrings)
        {
            StreamReader streamReader = new StreamReader(pathRead);
            if (File.Exists(pathWrite))
            {
                File.Delete(pathWrite);
            }
            StreamWriter streamWriter = new StreamWriter(pathWrite, false, Encoding.GetEncoding("utf-8"));
            string text = streamReader.ReadToEnd();
            if (replaceStrings != null && replaceStrings.Count > 0)
            {
                foreach (System.Collections.Generic.KeyValuePair<string, string> current in replaceStrings)
                {
                    text = text.Replace(current.Key, current.Value);
                }
            }
            streamWriter.WriteLine(text);
            streamReader.Close();
            streamWriter.Close();
        }
        /// <summary>
        /// 读取文件，返回文件内容
        /// </summary>
        /// <param name="filePath">附件路径</param>
        /// <returns>文件内容</returns>
        public static string ReadFile(string filePath)
        {
            StreamReader streamReader = new StreamReader(filePath);
            string result = null;
            if (File.Exists(filePath))
            {
                result = streamReader.ReadToEnd();
            }
            streamReader.Close();
            return result;
        }
        /// <summary>
        /// 写文件，utf-8的格式
        /// </summary>
        /// <param name="pathWrite">写入路径</param>
        /// <param name="content">写入字符串</param>
        public static void WriteFile(string pathWrite, string content)
        {
            if (File.Exists(pathWrite))
            {
                File.Delete(pathWrite);
            }
            StreamWriter streamWriter = new StreamWriter(pathWrite, false, Encoding.GetEncoding("utf-8"));
            streamWriter.WriteLine(content);
            streamWriter.Close();
        }
        /// <summary>
        /// 读取并将字符串追加到文件中，utf-8的格式
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="content">追加的字符串</param>
        public static void ReadAndAppendFile(string filePath, string content)
        {
            File.AppendAllText(filePath, content, Encoding.GetEncoding("utf-8"));
        }
        /// <summary>
        /// 拷贝文件（覆盖拷贝）
        /// </summary>
        /// <param name="sources">原文件路径</param>
        /// <param name="dest">目标路径</param>
        public static bool CopyFile(string sources, string dest)
        {
            //检查源文件是否存在
            if (!IsExistFile(sources))
            {
                //不存在返回失败
                return false;
            }
            //目标文件
            FileInfo destFile = new FileInfo(dest);
            //目标文件父目录不存在，就创建
            if (!Directory.Exists(destFile.DirectoryName))
            {
                Directory.CreateDirectory(destFile.DirectoryName);
            }
            //覆盖拷贝
            File.Copy(sources, dest, true);

            return true;
        }
        /// <summary>
        /// 移动文件
        /// 如果源文件不存在返回false
        /// 如果目标文件存在，则前删除后移动
        /// </summary>
        /// <param name="sources">源文件路径</param>
        /// <param name="dest">目标文件路径</param>
        public static bool MoveFile(string sources, string dest)
        {
            //检查源文件是否存在
            if (!IsExistFile(sources))
            {
                //不存在返回失败
                return false;
            }

            //目标文件
            FileInfo destFile = new FileInfo(dest);
            //目标文件父目录不存在，就创建
            if (!Directory.Exists(destFile.DirectoryName))
            {
                Directory.CreateDirectory(destFile.DirectoryName);
            }
            //如果目标文件已经存在，先删除在拷贝
            if (IsExistFile(dest))
            {
                DeleteFile(dest);
            }
            //覆盖拷贝
            File.Move(sources, dest);

            return true;
        }
        /// <summary>
        /// 是否存在文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool IsExistFile(string filePath)
        {
            return File.Exists(filePath);
        }

        #endregion
    }
}
